#include <QContextMenuEvent>
#include <QMenu>
#include <QX11Info>

#include "dexpanelbtn.h"

DexPanelBtn::DexPanelBtn(const QString &text, QWidget * parent) : QPushButton(text, parent)
	{
		createMenu();
		connect(this, SIGNAL(clicked(bool)), this, SLOT(pressed(bool)));
	}

void DexPanelBtn::mousePressEvent(QMouseEvent *event)
	{
		if (event->button() == Qt::LeftButton)
		{
			if (isChecked())
				minimize();
			else
				restore();
			event->ignore();
		}
	}

void DexPanelBtn::contextMenuEvent(QContextMenuEvent *event)
	{
		if (event->type() == QContextMenuEvent::ContextMenu)
			showMenu();
	}

void DexPanelBtn::createMenu()
	{
		menu = new QMenu(this);
		minimizeAction = menu->addAction(tr("&Minimize"), this, SLOT(minimize()));
//		addAction(minimizeAction);
		if (isChecked())
			minimizeAction->setVisible(false);
		else
			minimizeAction->setVisible(true);
		restoreAction = menu->addAction(tr("&Restore"), this, SLOT(restore()));
//		addAction(restoreAction);
		if (isChecked())
			restoreAction->setVisible(true);
		else
			restoreAction->setVisible(false);
		addAction(menu->addSeparator());
		/*addAction(*/menu->addAction(tr("&Close"), this, SLOT(closeWindow()));//);
		setMenu(menu);
	}

void DexPanelBtn::pressed(bool x)
	{
		if (x) restore();
		else minimize();
	}

void DexPanelBtn::closeWindow()
	{
		sendClientMessage(XInternAtom(QX11Info::display(), "WM_PROTOCOLS", False),
						  win,
						  XInternAtom(QX11Info::display(), "WM_DELETE_WINDOW", FALSE),
						  0L);
	}

void DexPanelBtn::minimize()
	{
		sendClientMessage(XInternAtom(QX11Info::display(), "WM_CHANGE_STATE", False),
						  QX11Info::appRootWindow(QX11Info::appScreen()),
						  IconicState,
						  (SubstructureNotifyMask | SubstructureRedirectMask));
		minimizeAction->setVisible(false);
		restoreAction->setVisible(true);
		setChecked(false);
	}

void DexPanelBtn::restore()
	{
		sendClientMessage(XInternAtom(QX11Info::display(), "_NET_ACTIVE_WINDOW", False),
						  QX11Info::appRootWindow(QX11Info::appScreen()),
						  0L,
						  (SubstructureNotifyMask | SubstructureRedirectMask));
		minimizeAction->setVisible(true);
		restoreAction->setVisible(false);
		setChecked(true);
	}

void DexPanelBtn::sendClientMessage(Atom messageType, Window seWin, long data, long eventMask)
	{
		Display *dpy = QX11Info::display();
		XEvent event;
		memset(&event, 0, sizeof(event));
		event.type = ClientMessage;
		event.xclient.type = ClientMessage;
		event.xclient.display = dpy;
		event.xclient.window = win;
		event.xclient.message_type = messageType;
		event.xclient.format = 32;
		event.xclient.data.l[0] = data;
		XSendEvent(dpy, seWin, false, eventMask, &event);
	}

void DexPanelBtn::setWindow(Window w)
	{
		win = w;
	}
